package murphyhan;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class Route {

	ArrayList placemarks = new ArrayList();
	private int pointsDivide = 0;

	private Element findElement(Element aElement, String name) {
		Element element = null;
		for (Iterator iterator = aElement.getChildren().iterator(); iterator
				.hasNext();) {
			element = (Element) iterator.next();
			if (name.equals(element.getName())) {
				return element;
			}
		}

		return element;
	}

	public Route(InputStream in, Iterator photoBuilder, int shiftHours,
			int pointsDivide) {
		try {
			SAXBuilder bSAX = new SAXBuilder(false);
			Document docJDOM = bSAX.build(in);
			this.go(docJDOM, photoBuilder, shiftHours, pointsDivide);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Route(Document docJDOM, Iterator photoBuilder, int shiftHours,
			int pointsDivide) {
		try {
			this.go(docJDOM, photoBuilder, shiftHours, pointsDivide);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public Route(String gpxFile, Iterator photoBuilder, int shiftHours,
			int pointsDivide) {
		InputStream in = null;
		try {
			URL url = new URL(gpxFile);

			URLConnection conn = url.openConnection();

			// setting these timeouts ensures the client does not deadlock
			// indefinitely
			// when the server has problems.
			conn.setConnectTimeout(10 * 1000);
			conn.setReadTimeout(10 * 1000);
			in = conn.getInputStream();
			SAXBuilder bSAX = new SAXBuilder(false);
			Document docJDOM = bSAX.build(in);
			this.go(docJDOM, photoBuilder, shiftHours, pointsDivide);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void go(Document docJDOM, Iterator photoBuilder, int shiftHours,
			int pointsDivide) {

		this.pointsDivide = pointsDivide;



		try {

			// Iterator photoBuilder = new PhotoBuilder(photoFile);


			Element elmtRoot = docJDOM.getRootElement();

		

			// Element trk = (Element) elmtRoot.getChildren().get(0);
			Element trk = this.findElement(elmtRoot, "trk");
			Element trkseq = this.findElement(trk, "trkseq");
			List trkpts = trkseq.getChildren();
			// lstChildren.size()
			int i = -1;

			boolean isFirst = true;
			while (photoBuilder.hasNext()) {
				Photo photo = (Photo) photoBuilder.next();
				Path path = new Path();
				// System.out.println(photo.toString());

				GLatLng lastGLatLng = new GLatLng((Element) trkpts.get(0), shiftHours);
				while (true) {
					i++;

					Element trkpt = (Element) trkpts.get(i);
					GLatLng gLatLng = new GLatLng(trkpt,shiftHours);
					path.add(gLatLng);

					// double eleRate = gLatLng.getAltitudeRate(lastGLatLng);
					//
					// if (eleRate > 1.3) {
					// System.out.println(i + " " + gLatLng.toString()
					// + " eleRate=" + eleRate);
					//
					// continue;
					// }
					//
					// if (eleRate < 0) {
					// System.out.println(i + " " + gLatLng.toString()
					// + " eleRate=" + eleRate);
					//
					// continue;
					// }
					// lastGLatLng = gLatLng;

					try {
						if (isFirst) {
							isFirst = false;
							Path tmpPath = new Path();
							tmpPath.add(gLatLng);
							Placemark placemark = new Placemark(null, tmpPath);
							placemarks.add(placemark);
						}

			
						boolean isLastPoint = i == trkpts.size() - 1;
						if (gLatLng.time.after(photo.time) || isLastPoint) {
							Placemark placemark = new Placemark(photo, path);
							System.out.println(photo.time + " " + placemark);
							placemarks.add(placemark);
							i--;
							break;
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						break;
					}
				}
			}
		}

		catch (Exception e) {

			e.printStackTrace();

			return;

		}


		// OutputXML(docJDOM, "e:/myJDOM2.xml");

	}

	private void readPhoto() {

	}

	private Date getDate(String time) throws Exception

	{

		// >2008-09-02T21:17:15Z<

		java.util.Date date =

		new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(time);

		return date;

	}

	private void OutputXML(Document docXML, String strFilename) {

		XMLOutputter fmt = new XMLOutputter();

		try {

			Format format = Format.getPrettyFormat();
			format = format.setEncoding("big5");
			// fmt.setEncoding("big5");

			// fmt.setNewlines(true);

			fmt.setFormat(format);

			// FileWriter fwXML = new FileWriter(strFilename);
			//
			// fmt.output(docXML, fwXML);
			//
			// fwXML.close();

		}

		catch (Exception e) {

			e.printStackTrace();

		}

	}

	public static void main(String[] args) {

		String routeName = "0608";
		// 1. picasa rss url
		// String photopath =
		// "http://picasaweb.google.com/data/feed/base/user/murphyhan/albumid/5347564263628360673?alt=rss&kind=photo&hl=en_US";
		// 2. local photo path
		// String photopath = "D:\\My Pictures\\Picasa\\" + routeName;
		String photopath = "D:\\My Pictures\\2009\\0608";
		String gpx = "C:\\Program Files\\GlobalSat Technology Corporation\\Data Logger PC Utility\\gpx\\"
				+ routeName + ".gpx";

		photopath = "D:\\My Pictures\\Picasa\\hm320";
		gpx = "C:\\Program Files\\GlobalSat Technology Corporation\\Data Logger PC Utility\\gpx\\.gpx";
		try {
			photopath = args[0];
		} catch (Exception e1) {

		}

		try {
			gpx = args[1];
		} catch (Exception e1) {

		}

		int shiftHours = 8;

		try {
			shiftHours = Integer.parseInt(args[2]);
		} catch (Exception e1) {

		}

		int pointDivide = 1;

		try {
			pointDivide = Integer.parseInt(args[3]);
		} catch (Exception e1) {

		}

		Iterator photoBuilder = null;
		if (photopath.startsWith("http:")) {
			photoBuilder = new PicasaPhotoBuilder(photopath);
		} else {
			photoBuilder = new PhotoBuilder(photopath);
		}

		Route myRead1 = new Route(gpx, photoBuilder, shiftHours, pointDivide);
		String outPutFile = "./liveroam.txt";
		try {
			// FileWriter bw = new FileWriter(outPutFile);

			// BufferedWriter bw = new BufferedWriter(write);

			StringBuffer sb = new StringBuffer();

			String p = myRead1.showPlacemarks();
			sb.append(p);
			sb.append("\n\n");
			String s = myRead1.showPics();
			sb.append(s);
			sb.append("\n\n");
			String pth = myRead1.showPaths();

			sb.append(pth);
			sb.append("\n\n");
			// String allPth = myRead1.showAllPaths();
			// sb.append(allPth);

			sb.append("\n");
			// fw.write(myRead1.showPathsEncode());
			sb.append("\n");

			if (photoBuilder instanceof PicasaPhotoBuilder) {
				String albumUrl = ((PicasaPhotoBuilder) photoBuilder)
						.getAlbumUrl();
				sb.append("var _albumUrl =\"" + albumUrl);
				sb.append("\";");
				sb.append("\n");
				sb.append("var _albumTitle =\""
						+ ((PicasaPhotoBuilder) photoBuilder).getAlbumTitle());
				sb.append("\";");
				sb.append("\n");

			}

			System.out.println(sb.toString());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}




	public String showPaths() {

		int routeCount = 0;
		StringBuffer re = new StringBuffer();
		re.append("var routePointsData =");
		re.append("[");
		for (int i = 0, j = this.placemarks.size(); i < j; i++) {
			Placemark placemark = (Placemark) placemarks.get(i);
			re.append(placemark.path.getPoints(pointsDivide));
			re.append(",");

			routeCount = routeCount
					+ placemark.path.getPointsCount(pointsDivide);
		}
		re.deleteCharAt(re.length() - 1);
		re.append("]");
		re.append(";");
		re.append("\n//routeCount[");
		re.append(routeCount);
		re.append("]");

		System.out.println("routeCount===" + routeCount);
		return re.toString();
	}

	public String showAllPaths() {

		StringBuffer re = new StringBuffer();
		re.append("var allRoutePointsData =");
		re.append("[");
		for (int i = 0, j = this.placemarks.size(); i < j; i++) {
			Placemark placemark = (Placemark) placemarks.get(i);
			re.append(placemark.path.getPathPoints());
			re.append(",");
		}
		re.deleteCharAt(re.length() - 1);
		re.append("]");
		re.append(";");

		// System.out.println(re.toString());
		return re.toString();
	}

	public String showPics() {
		StringBuffer re = new StringBuffer();
		re.append("var pics =");
		re.append("[");
		for (int i = 0, j = this.placemarks.size(); i < j; i++) {
			Placemark placemark = (Placemark) placemarks.get(i);

			if (i == 0) {
				re
						.append("\"http://code.google.com/apis/picasaweb/images/wwpicasa190x50.gif\"");
				re.append(",");
			} else if (i == placemarks.size() - 1) {
				re
						.append("\"http://lh4.ggpht.com/_x99qY4ZVFFI/SQmf5DXGSWI/AAAAAAAAE94/NSHP7e4c6JM/end.jpg\"");
				re.append(",");
			} else if (placemark.photo == null) {
				re.append("\"\"");
				re.append(",");
			} else {
				re.append(placemark.photo.getUrl());
				re.append(",");
			}
		}

		re.deleteCharAt(re.length() - 1);
		re.append("]");
		re.append(";");

		// System.out.println(re.toString());
		return re.toString();

	}

	public String showPlacemarks() {
		StringBuffer re = new StringBuffer();
		re.append("var placemarks =");
		re.append("[");
		for (int i = 0, j = this.placemarks.size(); i < j; i++) {
			Placemark placemark = (Placemark) placemarks.get(i);
			re.append(placemark.getMe(i));
			re.append(",");
		}
		re.deleteCharAt(re.length() - 1);
		re.append("]");
		re.append(";");

		// System.out.println(re.toString());
		return re.toString();

	}

}
